<?php 

declare(strict_types=1);

namespace WanZ\App\Utils\Prometheus;

use Prometheus\Exception\MetricsRegistrationException;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;

/**
 * Class Brother
 * @package WanZ\App\Utils\Prometheus
 *
 * @property WanZ\App\Utils\Prometheus\Brother device
 * @property WanZ\App\Utils\Prometheus\Brother pay
 * @property WanZ\App\Utils\Prometheus\Brother public
 * @property WanZ\App\Utils\Prometheus\Brother public_pay
 * @property WanZ\App\Utils\Prometheus\Brother icc
 * @property WanZ\App\Utils\Prometheus\Brother rate
 *
 */
class Brother extends Prometheus
{
    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * 记录调用兄弟服务错误次数
     *
     * @param string $url
     * @param string $serName
     * @param int $errorNum
     */
    public function addErrorNumToBrotherService(string $url, string $serName = '', int $errorNum = 1)
    {
        $serParams['ser_url'] = $url;

        if (!empty($serName)) {
            $serParams['ser_name'] = $serName;
        }

        $this->incBy(
            $this->getDefaultNamePrefix(),
            $this->getDefaultName(),
            $this->getHelpMsgBySerType(),
            array_merge($this->getDefaultLabel(), $serParams),
            $errorNum
        );
    }

    /**
     * 记录调用兄弟服务错误次数
     *
     * @param $name
     * @throws MetricsRegistrationException
     */
    public function __get($serviceType)
    {
        try {
            $this->incBy(
                $this->getDefaultNamePrefix(),
                $this->getDefaultName(),
                $this->getHelpMsgBySerType(),
                array_merge($this->getDefaultLabel(), ['ser_type' => $serviceType])
            );
        } catch (\Throwable $exception) {
            $this->logger->error('prometheusBrotherError', [
                'errorMsg' => $exception->getMessage(),
                'site' => $exception->getFile() .'|'. $exception->getLine()
            ]);             
        }
    }

    /**
     * 记录请求内部兄弟服务失败次数
     */
    private function getHelpMsgBySerType(): string
    {
        return '请求内部兄弟服务发生错误';
    }

    /**
     * 获取默认指标名前缀
     * @return string
     */
    private function getDefaultNamePrefix(): string
    {
        return 'brother_ser';
    }

    /**
     * 获取默认指标名
     * @return string
     */
    private function getDefaultName(): string
    {
        return 'request_error_total';
    }

    /**
     * 获取默认标签
     * @return array
     */
    private function getDefaultLabel(): array
    {
        return $this->getCompanyIdAndUType();
    }
}
